// 引入axios核心库
import router from '@/router'
import axios from 'axios'
// 引入queryString
import qsString from 'querystring'
let baseUrl = '/api'
// 引入拦截器
// 请求拦截
axios.interceptors.request.use(req => {
    if (req.url == '/api/userlogin') {
        return req
    } else {
        // 全局添加token请求头
        req.headers.authorization = sessionStorage.getItem('userinfo') ? JSON.parse(sessionStorage.getItem('userinfo')).token : null
        return req
    }


})
// 响应拦截
axios.interceptors.response.use(res => {
    // console.log(res);
    // 全局拦截错误
    if (res.data.msg == '请设置请求头,并携带验证字符串') {
        router.push('/login')
    }
    if (res.data.code == 403) {
        console.log(res);
        router.push('/login')
    }
    return res.data
})


// 封装请求方式
/*
get
url  接口地址
params  入参
*/
export const get = (url, params = {}) => {
    return new Promise((resolve, reject) => {
        axios.get(baseUrl + url, {
            params
        }).then(res => resolve(res))
            .catch(err => reject(err))
    })
}

/*
post
url  接口地址
params 入参
isFile  是否有文件
*/

export const post = (url, params = {}, isFile = false) => {
    let data = {}
    if (isFile) {
        data = new FormData()
        for (let i in params) {
            data.append(i, params[i])
        }
    } else {
        data = qsString.stringify(params)
    }

    return new Promise((resolve, reject) => {
        axios.post(baseUrl + url, data)
            .then(res => resolve(res))
            .catch(err => reject(err))
    })
}